package com.ego.service.impl;

import com.ego.auth.entity.UserInfo;
import com.ego.client.GoodsClient;
import com.ego.exception.EgoException;
import com.ego.exception.ExceptionEnum;
import com.ego.interceptor.LoginInterceptor;
import com.ego.pojo.Cart;
import com.ego.pojo.Foot;
import com.ego.pojo.Sku;
import com.ego.pojo.utils.JsonUtils;
import com.ego.properties.JwtProperties;
import com.ego.service.CartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author Ares
 * @date 2020-12-10
 */
@Service
@EnableConfigurationProperties(JwtProperties.class)
@Slf4j
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private GoodsClient goodsClient;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public static final String KEY_PREFIX = "ego:cart:uid:";

    public final static String FOOT_KEY_PRE = "ego:foot:";

    @Override
    public void addCart(Cart cart) {
        // 获取登录用户
        UserInfo user = LoginInterceptor.getLoginUser();
        // Redis的key
        String key = KEY_PREFIX + user.getId();
        // 获取hash操作对象
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(key);
        // 查询是否存在
        Long skuId = cart.getSkuId();
        Integer num = cart.getCount();
        Boolean boo = hashOps.hasKey(skuId.toString());
        if (boo) {
            // 存在，获取购物车数据
            String json = hashOps.get(skuId.toString()).toString();
            cart = JsonUtils.parse(json, Cart.class);
            // 修改购物车数量
            cart.setCount(cart.getCount() + num);
        } else {
            // 不存在，新增购物车数据
            // 其它商品信息， 需要查询商品服务
            Sku sku = goodsClient.querySkuById(skuId).getBody();
            cart.setImage(StringUtils.isBlank(sku.getImages()) ? "" : StringUtils.split(sku.getImages(), ",")[0]);
            cart.setPrice(sku.getPrice());
            cart.setTitle(sku.getTitle());
            cart.setOwnSpec(sku.getOwnSpec());
        }
        // 将购物车数据写入redis
        hashOps.put(user.getId().toString(), JsonUtils.serialize(cart));
    }

    @Override
    public List<Cart> findCart(String token) {
        UserInfo userInfo = LoginInterceptor.getLoginUser();
        //查询当前用户所有的购物车数据
        List<Cart> result = null;

        try {
            result = stringRedisTemplate.opsForHash().values(KEY_PREFIX + userInfo.getId())
                    .stream()
                    .map(cartJson -> JsonUtils.parse(cartJson.toString(), Cart.class))
                    .collect(Collectors.toList());
        } catch (Exception e) {
            EgoException.error(log, ExceptionEnum.CART_QUERY_EXCEPTION,e);
        }
        return result;
    }

    @Override
    public Integer addFoot(Foot foot) {
        try {
            Long skuId = foot.getSkuId();
            Sku sku = goodsClient.querySkuById(foot.getSkuId()).getBody();

            foot.setImage(sku.getImages());
            foot.setPrice(sku.getPrice());
            foot.setTitle(sku.getTitle());

            UserInfo userInfo = LoginInterceptor.getLoginUser();

            stringRedisTemplate.opsForHash().put(FOOT_KEY_PRE + userInfo.getId(), skuId.toString(), JsonUtils.serialize(foot));
            stringRedisTemplate.expire(FOOT_KEY_PRE + userInfo.getId(),1, TimeUnit.DAYS);

        } catch (Exception e) {
            EgoException.error(log, ExceptionEnum.FOOT_ADD_EXCEPTION,e);
        }
        return 1;
    }

    @Override
    public List<Foot> findFoot(String token) {
        UserInfo userInfo = LoginInterceptor.getLoginUser();

        List<Foot> result = null;
        try {

            result = stringRedisTemplate.opsForHash().values(FOOT_KEY_PRE + userInfo.getId())
                    .stream()
                    .map(footJson -> JsonUtils.parse(footJson.toString(), Foot.class))
                    .collect(Collectors.toList());

        } catch (Exception e) {
            EgoException.error(log,ExceptionEnum.CART_QUERY_EXCEPTION,e);
        }
        return result;
    }


}
